const Router = require('koa-router');
const fs = require('await-fs');
const path = require('path');
const common = require('../../libs/common');


let router = new Router;
// 路由规则

    // 页面请求
    router.get('/login', async ctx => {
        await ctx.render('admin/login', {
            HTTP_ROOT:ctx.config.HTTP_ROOT,
            errmsg:ctx.query.errmsg
        })
    })

    // 登录请求
    router.post('/login', async ctx => {
        let {HTTP_ROOT} = ctx.config;

        let {username, password} = ctx.request.fields;
        let admins = JSON.parse((await fs.readFile(
            path.resolve(__dirname, '../../admins.json')
        )).toString())

        // 查询管理员函数
        function findAdmin(username) {
            let user = null;
            admins.forEach(admin => {
                if(admin.username == username) {
                    user = admin
                }
            })
            return user
        }

        // 得到查找结果
        let admin = findAdmin(username);
        if (!admin) { // 检查账号
            ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('没有此用户')}`)
        } else if (admin.password != common.md5(ctx.config.ADMIN_PREFIX + password) ) {  // 检查密码
            ctx.redirect(`${HTTP_ROOT}/admin/login?errmsg=${encodeURIComponent('密码有误')}`)
        } else { // 登录成功
            ctx.session['admin'] = username;
            ctx.redirect(`${HTTP_ROOT}/admin/`)
        }
    })

    // 统一拦截检查是否管理员
    router.all('*', async (ctx, next) => {
        let {HTTP_ROOT} = ctx.config;
        if (ctx.session['admin']) {
            await next()
        } else {
            ctx.redirect(`${HTTP_ROOT}/admin/login`)
        }
    })

    // 设置admin根路由
    router.get('/', async ctx => {
        let {HTTP_ROOT} = ctx.config;
        ctx.redirect(`${HTTP_ROOT}/admin/banner`);
    })

    // 分发功能区块路由
    router.use('/banner', require('./banner'));
    router.use('/catalog', require('./catalog'))
    router.use('/article', require('./article'))

// 导出路由
module.exports = router.routes();
